package cn.nami.web.frontpage.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.nami.web.frontpage.entity.User;
import cn.nami.web.frontpage.jdo.UserJdo;
import cn.nami.web.util.JsonUtil;
import cn.nami.web.util.UserUtil;

public class LoginServlet extends HttpServlet
{
	private static final long serialVersionUID = 1518846265999617068L;
	
	private static final String USER_SESSION_KEY = User.class.getName();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String method = request.getParameter("method");
		if("login".equals(method))
		{
			login(request, response);
		}
		else if("logout".equals(method))
		{
			logout(request, response);
		}
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User(username, password);

		Map<String, String> map = new HashMap<String, String>();
		if(UserUtil.isAdmin(username, password))
		{
			request.getSession().setAttribute(USER_SESSION_KEY, user);
			map.put("flag", "1");
		}
		else
		{
			user = UserJdo.getByName(username);
			if(user == null)
			{
				map.put("flag", "0");
				map.put("user", "User not exist!");
			}
			else if(user.getPassword().equals(password))
			{
				request.getSession().setAttribute(USER_SESSION_KEY, user);
				map.put("flag", "1");
			}
			else
			{
				map.put("flag", "0");
				map.put("password", "Password is error, please check!");
			}
		}
		PrintWriter out = response.getWriter();
		JsonUtil.setJsonHeader(response);
		out.print(JsonUtil.toJson(map));
		out.flush();
		out.flush();
	}
	
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.getSession().removeAttribute(USER_SESSION_KEY);
		response.sendRedirect(request.getContextPath());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request, response);
	}
}
